package com.itboye.hutouben.activity.driverrepair;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.addressmanage.AddressListActivity;
import com.itboye.hutouben.activity.store.GoPayActivity;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.bean.GoPayBean;
import com.itboye.hutouben.bean.MoneyShengyuBean;
import com.itboye.hutouben.bean.MyAddressBean;
import com.itboye.hutouben.bean.RepairBean;
import com.itboye.hutouben.presenter.DingDanPresenter;
import com.itboye.hutouben.presenter.SysTemMessgelPresenter;
import com.itboye.hutouben.presenter.SystemMessgeAPresenter;
import com.itboye.hutouben.presenter.UserPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.MathUtil;
import com.itboye.hutouben.util.UIAlertView02;
import com.itboye.hutouben.volley.ResultEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.hutouben.util.MathUtil.sub;

/**
 * 报修金额
 */
public class ActivityZhifu extends BaseActivity implements Observer {
    TextView tvweixiu, tvcailiao, tvzongji, zhifutv, tvOk, add_shap_title_tv;
    String id;
    ImageView close_icon;
    DingDanPresenter dingDanPresenter;
    SysTemMessgelPresenter messgelPresenter;
    GoPayBean list;
    TextView order_jifen, order_jian, order_jia;
    EditText order_num;
    SystemMessgeAPresenter presenter;
    MoneyShengyuBean yeBean;
    double zongMoney;//总价
    String score;//积分
    String score_rate;//积分比例

    private UIAlertView02 uiAlertView;

    RelativeLayout order_type, order_taitou, order_shuihao;//选择发票类型，发票抬头，添加税号
    TextView tv_type;//发票类型
    EditText et_taitou, et_shuihao;//抬头，税号
    private OptionsPickerView pvOptions;

    String type = "";//发票类型(1=>个人,2=>企业)[可选],int
    String taitou;//发票抬头
    String shuihao;//发票税号
    RelativeLayout choose_address;//地址
    TextView address_people, address_phone, address_detail;
    String adressId = "";//收货地址id
    MyAddressBean bean;

    UserPresenter userPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_baoxiu);
        add_shap_title_tv.setText("报修金额");
        dingDanPresenter = new DingDanPresenter(this);
        presenter = new SystemMessgeAPresenter(this);
        userPresenter = new UserPresenter(this);
        getOptionData();
        initOptionPicker();
        yeBean = new MoneyShengyuBean();
        showProgressDialog("获取价格中,请稍后", true);
        userPresenter.queryAddress(IsUtilUid.sId(), IsUtilUid.isUid());
        messgelPresenter = new SysTemMessgelPresenter(this);
        messgelPresenter.onByRepairCurrent(IsUtilUid.isUid(), "6");

        list = (GoPayBean) getIntent().getSerializableExtra("bean");
        id = getIntent().getStringExtra("id");
        order_num.addTextChangedListener(watcher);
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.onMoney(IsUtilUid.isUid());
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    String returnedData = data.getStringExtra("data_return");
                    address_people.setText("收货人:" + data.getStringExtra("name"));
                    adressId = data.getStringExtra("id");
                    address_phone.setText(data.getStringExtra("phone"));
                    address_detail.setText("收货地址:" + data.getStringExtra("addaress"));
                }
                break;
            default:
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dingDanPresenter.quxiaoZhifu(IsUtilUid.isUid(), getIntent().getStringExtra("id"));
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                dingDanPresenter.quxiaoZhifu(IsUtilUid.isUid(), getIntent().getStringExtra("id"));
                finish();
                break;
            case R.id.tvOk:
                taitou = et_taitou.getText().toString().trim();
                shuihao = et_shuihao.getText().toString().trim();
                if (type.equals("1")) {
                    if (taitou.equals("")) {
                        ByAlert.alert("请输入发票抬头");
                        return;
                    }
                    if (adressId.equals("")) {
                        ByAlert.alert("请添加收货地址");
                        return;
                    }
                } else if (type.equals("2")) {
                    if (taitou.equals("")) {
                        ByAlert.alert("请输入发票抬头");
                        return;
                    }
                    if (shuihao.equals("")) {
                        ByAlert.alert("请输入发票税号");
                        return;
                    }
                    if (adressId.equals("")) {
                        ByAlert.alert("请添加收货地址");
                        return;
                    }
                }
                String moneyss = zhifutv.getText().toString().substring(1, zhifutv.getText().toString().length());
                if (Double.parseDouble(moneyss) < 0) {
                    ByAlert.alert("你见过负数能支付吗？");
                }
                if (Double.parseDouble(moneyss) == 0) {
                    uiAlertView = new UIAlertView02(ActivityZhifu.this, "是否消耗积分", "免额支付", "确定", "取消");
                    uiAlertView.show();
                    uiAlertView.setClicklistener(new UIAlertView02.ClickListenerInterface() {
                        @Override
                        public void doLeft() {
                            showProgressDialog("正在支付,请稍后", true);
                            messgelPresenter.onZhiFuTwo(IsUtilUid.isUid(), id, order_num.getText().toString(), type, taitou, shuihao, adressId);
                            uiAlertView.dismiss();
                        }
                        @Override
                        public void doRight() {
                            uiAlertView.dismiss();
                        }
                    });
                    return;
                } else {
                    showProgressDialog("正在支付,请稍后", true);
                    messgelPresenter.onZhiFu(IsUtilUid.isUid(), id, order_num.getText().toString(), type, taitou, shuihao, adressId);
                }
                break;
            case R.id.order_type:
                pvOptions.show();
                break;
            case R.id.choose_address://收货地址
                Intent intent = new Intent(this, AddressListActivity.class);
                intent.putExtra("type", "1");
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            //维修（进行中）
            if (entity.getEventType() == messgelPresenter.Repair_current_success) {
                RepairBean beans= (RepairBean) entity.getData();
                String repair_price = beans.getRepair_price();//维修费
                String stuff_price = beans.getStuff_price();//材料费
                String price = beans.getPrice();//总费用

                tvweixiu.setText("¥" + Double.parseDouble(repair_price) / 100 + "");
                tvcailiao.setText("¥" + Double.parseDouble(stuff_price) / 100 + "");
                tvzongji.setText("¥" + Double.parseDouble(price) / 100 + "");
                zhifutv.setText("¥" + Double.parseDouble(price) / 100 + "");
                zongMoney = Double.parseDouble(price) / 100;
            }
            if (entity.getEventType() == messgelPresenter.Repair_current_fail) {

            }
            //去支付(积分)
            if (entity.getEventType() == SysTemMessgelPresenter.zhifu_twos_success) {
                ByAlert.alert("支付完成");
                finish();
            }
            if (entity.getEventType() == SysTemMessgelPresenter.zhifu_twos_fail) {
                ByAlert.alert(entity.getData());
            }
            //去支付
            if (entity.getEventType() == SysTemMessgelPresenter.zhifu_success) {
                GoPayBean gobean = (GoPayBean) entity.getData();
                Intent intent = new Intent(this, GoPayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", gobean);
                intent.putExtras(bundle);
                intent.putExtra("type", "three");
                intent.putExtra("id", id);
                startActivity(intent);
                finish();
            }
            if (entity.getEventType() == SysTemMessgelPresenter.zhifu_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == presenter.Yue_success) {
                yeBean = (MoneyShengyuBean) entity.getData();
                jifen(yeBean);

            }
            if (entity.getEventType() == presenter.Yue_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.query_address_success) {
                List<MyAddressBean> list = (List<MyAddressBean>) entity.getData();
                if (list != null) {
                    if (list.size() > 0) {
                        userPresenter.getMoRenAddress(IsUtilUid.sId(), IsUtilUid.isUid());
                    } else {
                        // ByAlert.alert("没有默认收货地址，建议去添加");
                    }
                } else {
                    // ByAlert.alert("没有默认收货地址，建议去添加");
                }
            }
            if (entity.getEventType() == UserPresenter.query_address_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.moren_address_success) {
                bean = (MyAddressBean) entity.getData();
                address_people.setText("收货人:" + bean.getContactname());
                adressId = bean.getId() + "";
                address_phone.setText(bean.getMobile());
                address_detail.setText("收货地址:" + bean.getProvince() + bean.getCity() + bean.getArea() + bean.getDetailinfo());
            }
            if (entity.getEventType() == UserPresenter.moren_address_fail) {
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    /**
     * 操作积分
     *
     * @param bean
     */
    private void jifen(final MoneyShengyuBean bean) {
        score = bean.getScore();
        score_rate=bean.getScore_rate();
        order_jifen.setText(score);
        order_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (Double.parseDouble(score_rate) > zongMoney) {
                        ByAlert.alert("价格太少,积分不能使用");
                        return;
                    }

                    int c = 0;
                    if (!order_num.getText().toString().equals("")) {
                        c = Integer.parseInt(order_num.getText().toString());
                    }
                    if (c >= Integer.parseInt(score)) {
                        return;
                    }
                    if (sub(zongMoney, MathUtil.mul(c, Double.parseDouble(score_rate))) <= 0) {

                        return;
                    }
                    order_num.setText(c + 1 + "");
                    zhifutv.setText("¥" + sub(zongMoney, MathUtil.mul(c + 1, Double.parseDouble(score_rate))));

                    if (sub(zongMoney, MathUtil.mul(c - 1, Double.parseDouble(score_rate))) < 0) {
                        order_num.setText("0");
                        zhifutv.setText("¥" + zongMoney);
                        return;
                    }
                    if (order_num.getText().toString().equals("0")){
                        zhifutv.setText("¥" + zongMoney);
                    }
                } catch (NumberFormatException e) {
                    order_num.setText("0");
                    zhifutv.setText("¥" + zongMoney);
                }
            }
        });
        order_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int c = 0;
                    if (!order_num.getText().toString().equals("")) {
                        c = Integer.parseInt(order_num.getText().toString());
                    }
                    if (c <= 0) {
                        return;
                    }
                    order_num.setText(c - 1 + "");
                    zhifutv.setText("¥" + sub(zongMoney, MathUtil.mul(c - 1, Double.parseDouble(score_rate))));
                    if (order_num.getText().toString().equals("0")){
                        zhifutv.setText("¥" + zongMoney);
                    }
                } catch (NumberFormatException e) {
                    order_num.setText("0");
                    zhifutv.setText("¥" + zongMoney);
                }
            }
        });

    }

    /**
     * 输入数量时候的监听
     */
    TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //只要编辑框内容有变化就会调用该方法，s为编辑框变化后的内容
            Log.i("onTextChanged", s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //编辑框内容变化之前会调用该方法，s为编辑框内容变化之前的内容
            Log.i("beforeTextChanged", s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            //编辑框内容变化之后会调用该方法，s为编辑框内容变化后的内容
            Log.i("afterTextChanged", s.toString());
            if (!s.toString().equals("")) {
                int shuru = 0;
                if (!s.toString().equals("")) {
                    shuru = Integer.parseInt(s.toString());
                }
                if (shuru > Integer.parseInt(score)) {
                    order_num.setText("");
                    ByAlert.alert("没有这么多积分");
                    return;
                }
                if (order_num.getText().toString().equals("0")){
                    zhifutv.setText("¥" + zongMoney);
                }
                try {
                    if (sub(zongMoney, MathUtil.mul(shuru, Double.parseDouble(score_rate))) < 0) {
                        order_num.setText("0");
                        ByAlert.alert("该订单最多能使用" + MathUtil.div(zongMoney, Double.parseDouble(score_rate), 2) + "积分");
                        return;
                    }
                } catch (Exception e) {
                    order_num.setText("0");
                }
               zhifutv.setText("¥" + sub(zongMoney, MathUtil.mul(shuru, Double.parseDouble(score_rate))));
            }
        }
    };
    private ArrayList<String> options1Items = new ArrayList<>();

    /**
     * 选择发票抬头
     */
    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);
                tv_type.setText(tx);
                if (options1 == 0) {
                    type = "";
                    xianshi();
                } else if (options1 == 1) {
                    type = "1";
                    xianshi();
                    order_taitou.setVisibility(View.VISIBLE);
                    choose_address.setVisibility(View.VISIBLE);
                } else if (options1 == 2) {
                    type = "2";
                    xianshi();
                    order_taitou.setVisibility(View.VISIBLE);
                    order_shuihao.setVisibility(View.VISIBLE);
                    choose_address.setVisibility(View.VISIBLE);
                }
            }
        })
                .setTitleText("发票抬头类型")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptions.setPicker(options1Items);//1级选择器
    }

    private void getOptionData() {
        //选项1
        options1Items.add("无");
        options1Items.add("个人");
        options1Items.add("企业");
    }

    private void xianshi() {
        order_taitou.setVisibility(View.GONE);
        order_shuihao.setVisibility(View.GONE);
        choose_address.setVisibility(View.GONE);
    }
}
